import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../service/service_method.dart';
import 'package:url_launcher/url_launcher.dart';

/*
 * Description: 首页
 * date: 2020/2/8
 * author:ANSWER
 */

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  int page = 1;
  List<Map> hotGoodsList = [];

  //刷新controller
  EasyRefreshController _controller = EasyRefreshController();

  @override
  // 保持状态
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('首页'),
      ),
      body: FutureBuilder(
        future: request('homePageContent',
            formData: {'lon': '115.02932', 'lat': '35.76189'}),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            var data = json.decode(snapshot.data.toString());
            Map dataMap = data['data'];
            //轮播图数据
            List<Map> swiper = (dataMap['slides'] as List).cast();
            //导航数据
            List<Map> navigatorList = (dataMap['category'] as List).cast();
            if (navigatorList.length > 10) {
              navigatorList.removeRange(10, navigatorList.length);
            }
            //广告
            String adPicture = dataMap['advertesPicture']['PICTURE_ADDRESS'];
            //拨打电话
            String leaderImage = dataMap['shopInfo']['leaderImage'];
            String phone = dataMap['shopInfo']['leaderPhone'];
            //商品推荐
            List<Map> recommendList = (dataMap['recommend'] as List).cast();
            //楼层商品
            String floor1Title =
                data['data']['floor1Pic']['PICTURE_ADDRESS']; //楼层1的标题图片
            String floor2Title =
                data['data']['floor2Pic']['PICTURE_ADDRESS']; //楼层1的标题图片
            String floor3Title =
                data['data']['floor3Pic']['PICTURE_ADDRESS']; //楼层1的标题图片
            List<Map> floor1 =
                (data['data']['floor1'] as List).cast(); //楼层1商品和图片
            List<Map> floor2 =
                (data['data']['floor2'] as List).cast(); //楼层1商品和图片
            List<Map> floor3 =
                (data['data']['floor3'] as List).cast(); //楼层1商品和图片

            return EasyRefresh(
              header: ClassicalHeader(
                  refreshReadyText: '释放刷新',
                  refreshingText: '正在刷新',
                  refreshText: '下拉刷新',
                  refreshedText: '刷新完成',
                  infoText: '更新于 %T'),
              footer: ClassicalFooter(
                  infoText: '更新于 %T',
                  loadedText: '加载完成',
                  loadingText: '正在加载',
                  loadReadyText: '释放加载',
                  loadText: '上拉加载'),
              child: Column(
                children: <Widget>[
                  //轮播图
                  SwiperDiy(
                    swiperDataList: swiper,
                  ),
                  //导航
                  TopNavigator(
                    navigatorList: navigatorList,
                  ),
                  //广告
                  AdBanner(
                    adPicture: adPicture,
                  ),
                  //店长电话
                  LeaderPhone(
                    leaderImage: leaderImage,
                    phone: phone,
                  ),
                  //商品推荐
                  Recommend(
                    recommendList: recommendList,
                  ),
                  //楼层商品
                  FloorTitle(
                    pictureAddress: floor1Title,
                  ),
                  FloorContent(
                    floorGoodList: floor1,
                  ),
                  FloorTitle(
                    pictureAddress: floor2Title,
                  ),
                  FloorContent(
                    floorGoodList: floor2,
                  ),
                  FloorTitle(
                    pictureAddress: floor3Title,
                  ),
                  FloorContent(
                    floorGoodList: floor3,
                  ),
                  //热卖
                  _hotGoods(),
                ],
              ),
              onRefresh: () async {
                print('刷新');
                setState(() {
                  hotGoodsList.removeRange(1, hotGoodsList.length);
                });
              },
//              onRefresh: () async {
//                await Future.delayed(Duration(seconds: 2), () {
//                  if (mounted) {
//                    _controller.resetLoadState();
//                  }
//                });
//              },
              onLoad: () async {
                print('加载');
                request('homePageBelowConten', formData: {"page": 1})
                    .then((val) {
                  var data = json.decode(val.toString());
                  List<Map> newGoodsList = (data['data'] as List).cast();
                  setState(() {
                    hotGoodsList.addAll(newGoodsList);
                    page++;
                  });
                });
              },
            );
          } else {
            return Center(
              child: Text('加载中。。。'),
            );
          }
        },
      ),
    );
  }

  //火爆专区标题
  Widget hotTitle = Container(
    margin: EdgeInsets.only(top: 10.0),
    padding: EdgeInsets.all(5.0),
    alignment: Alignment.center,
    decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(width: 0.5, color: Colors.black12))),
    child: Text('火爆专区'),
  );

  //火爆专区子项
  Widget _wrapList() {
    if (hotGoodsList.length != 0) {
      List<Widget> listWidget = hotGoodsList.map((val) {
        return InkWell(
            onTap: () {
              print('点击了火爆商品');
            },
            child: Container(
              width: ScreenUtil().setWidth(372),
              color: Colors.white,
              padding: EdgeInsets.all(5.0),
              margin: EdgeInsets.only(bottom: 3.0),
              child: Column(
                children: <Widget>[
                  Image.network(
                    val['image'],
                    width: ScreenUtil().setWidth(375),
                  ),
                  Text(
                    val['name'],
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                  ),
                  Row(
                    children: <Widget>[
                      Text('￥${val['mallPrice']}'),
                      Text(
                        '￥${val['price']}',
                        style: TextStyle(
                            color: Colors.black26,
                            decoration: TextDecoration.lineThrough),
                      )
                    ],
                  )
                ],
              ),
            ));
      }).toList();

      return Wrap(
        spacing: 2,
        children: listWidget,
      );
    } else {
      return Text(' ');
    }
  }

  //火爆专区组合
  Widget _hotGoods() {
    return Container(
        child: Column(
      children: <Widget>[
        hotTitle,
        _wrapList(),
      ],
    ));
  }
}

//轮播图
class SwiperDiy extends StatelessWidget {
  List swiperDataList;

  SwiperDiy({Key key, this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(300),
      child: Swiper(
        itemCount: swiperDataList.length,
        itemBuilder: (context, index) {
          return Image.network(
            '${swiperDataList[index]['image']}',
            fit: BoxFit.fill,
          );
        },
        pagination: SwiperPagination(),
        autoplay: true,
      ),
    );
  }
}

//导航分类
class TopNavigator extends StatelessWidget {
  List navigatorList;

  TopNavigator({Key key, this.navigatorList}) : super(key: key);

  Widget _gridViewItemUI(BuildContext context, item) {
    return InkWell(
      onTap: () {
        print('点击了导航');
      },
      child: Column(
        children: <Widget>[
          Image.network(
            item['image'],
            width: ScreenUtil().setWidth(95),
          ),
          Text(item['mallCategoryName']),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(360),
      padding: EdgeInsets.all(15),
      child: GridView.count(
          crossAxisCount: 5,
          children: navigatorList.map((item) {
            //遍历list ，回调item 返回list
            return _gridViewItemUI(context, item);
          }).toList()),
    );
  }
}

//广告区域
class AdBanner extends StatelessWidget {
  String adPicture;

  AdBanner({Key key, this.adPicture}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Image.network(adPicture),
    );
  }
}

//店长电话拨打  模块
class LeaderPhone extends StatelessWidget {
  String leaderImage;
  String phone;

  LeaderPhone({Key key, this.leaderImage, this.phone}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: () {
          //打电话
          _launchURL();
        },
        child: Image.network(leaderImage),
      ),
    );
  }

  //拨打电话方法
  void _launchURL() async {
    String url = 'tel:' + phone;
    //判断是否能launch
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      print('url 不能访问$phone');
      throw 'url 不能访问';
    }
  }
}

//商品推荐
class Recommend extends StatelessWidget {
  List recommendList;

  Recommend({Key key, this.recommendList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10),
      child: Column(
        children: <Widget>[
          //小标题
          _titleWidget(),
          //横向列表
          _recommedList(),
        ],
      ),
    );
  }

  //小标题方法
  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10, 5, 0, 5),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(color: Colors.black12, width: 0.5),
        ),
      ),
      child: Text(
        '商品推荐',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  Widget _recommedList() {
    return Container(
      height: ScreenUtil().setHeight(360),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: recommendList.length,
        itemBuilder: (context, index) {
          return _item(index);
        },
      ),
    );
  }

  Widget _item(int index) {
    return InkWell(
      onTap: () {},
      child: Container(
        width: ScreenUtil().setWidth(250),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(left: BorderSide(width: 0.5, color: Colors.black12))),
        child: Column(
          children: <Widget>[
            Image.network(recommendList[index]['image']),
            Text('￥${recommendList[index]['mallPrice']}'),
            Text(
              '￥${recommendList[index]['price']}',
              style: TextStyle(
                  decoration: TextDecoration.lineThrough,
                  color: Colors.grey,
                  fontSize: ScreenUtil().setSp(24)),
            )
          ],
        ),
      ),
    );
  }
}

//楼层商品组件title
class FloorTitle extends StatelessWidget {
  String pictureAddress;

  FloorTitle({Key key, this.pictureAddress}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8.0),
      child: Image.network(pictureAddress),
    );
  }
}

//楼层商品组件content
class FloorContent extends StatelessWidget {
  List floorGoodList;

  FloorContent({Key key, this.floorGoodList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[_firstRow(), _otherGoods()],
      ),
    );
  }

//第一行
  Widget _firstRow() {
    return Row(
      children: <Widget>[
        _getItem(floorGoodList[0]),
        Column(
          children: <Widget>[
            _getItem(floorGoodList[1]),
            _getItem(floorGoodList[2]),
          ],
        )
      ],
    );
  }

//其他行
  Widget _otherGoods() {
    return Row(
      children: <Widget>[
        _getItem(floorGoodList[3]),
        _getItem(floorGoodList[4]),
      ],
    );
  }

  //单个可点击的item ==图片
  Widget _getItem(Map goods) {
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        onTap: () {
          print('你惦记了谁？');
        },
        child: Image.network(goods['image']),
      ),
    );
  }
}
